package com.book.utils;

import com.book.exception.GlobalException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author helen
 * @since 2019/10/16
 */
public class JwtUtils {

    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    public static final String APP_SECRET = "ukc8BDbRig@!^^&@#UDaY6pZFfWus2jZWLPHO";

    public static String getJwtToken(String id, String username){

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("book-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id)
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            Cookie[] cookies = request.getCookies();
            if(cookies != null){
                for(Cookie cookie : cookies){
                   if("JESSIONJWT".equals(cookie.getName())){
                       return checkToken(cookie.getValue());
                   }
                }
            }else{
                throw new GlobalException(500,"请登录！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    /**
     * 根据token获取会员username
     * @return
     */
    public static String getUsernameByJwtToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) throw new GlobalException(500,"token为空！！");
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("username");
    }


    /**
     * 根据token获取会员username
     * @return
     */
    public static String getUsernameByJwtToken(HttpServletRequest request) {

        try {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("JESSIONJWT".equals(cookie.getName())) {
//                        return getUsernameByJwtToken(cookie.getValue());
                        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(cookie.getValue());
                        Claims claims = claimsJws.getBody();
                        return (String) claims.get("username");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(500, "请登录！！");
        }
        throw  new GlobalException(500, "请登录！！");
    }


    /**
     * 根据token获取会员id
     * @return
     */
    public static String getIdByJwtToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) throw new GlobalException(500,"token为空！！");
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("id");
    }


    /**
     * 根据token获取会员id
     * @return
     */
    public static String getIdByJwtToken(HttpServletRequest request) {

        try {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if ("JESSIONJWT".equals(cookie.getName())) {
//                        return getUsernameByJwtToken(cookie.getValue());
                        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(cookie.getValue());
                        Claims claims = claimsJws.getBody();
                        return (String)claims.get("id");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(500, "请登录！！");
        }
        throw  new GlobalException(500, "请登录！！");
    }
}
